<template>
  <view class="indexPage">
    <view class="top-bg">
      <!-- <image mode="widthFix" style="width: 100vw;" src="/static/bgg.jpg" /> -->
    </view>
    <!-- 导航栏 -->
    <s-nav-bar title="订单列表" :background="'transparent'" :titleStyle="{ fontWeight: 'bold' }" statusBar back></s-nav-bar>

    <!-- 搜索过滤栏 -->
    <view class="fixed-filter">
      <view class="filter-bar">
        <picker mode="date" @change="changeDate" class="item">
          <view class="filter-item">
            <text>{{ filterDate || "全部日期" }}</text>
            <s-icon name="calendar-o" size="16" color="var(--v-gray)"></s-icon>
          </view>
        </picker>
        <picker @change="changeType" :range="typeOptions" range-key="text" class="item">
          <view class="filter-item">
            <text>{{ filterType || "全部类型" }}</text>
            <s-icon name="apps-o" size="16" color="var(--v-gray)"></s-icon>
          </view>
        </picker>
        <picker @change="changeStatus" :range="statusOptions" range-key="text" class="item">
          <view class="filter-item">
            <text>{{ filterStatus || "全部状态" }}</text>
            <s-icon name="balance-pay" size="16" color="var(--v-gray)"></s-icon>
          </view>
        </picker>
      </view>
    </view>

    <!-- 订单列表 -->
    <scroll-view class="main-scroll" scroll-y @scrolltolower="reachBottom" refresher-enabled
      :refresher-triggered="refreshing" @refresherrefresh="handleRefresh">
      <view class="order-list">
        <view v-for="(order, index) in processedOrderList" :key="index" class="order-card"
          :class="order.status == '已完成' ? 'disabled' : ''">
          <!-- 顶部信息 -->
          <view class="card-header">
            <text class="order-no">编号：{{ order.order_number }}</text>
            <text class="order-channel" :class="order.channelClass">渠道：{{ order.channel }}</text>
          </view>

          <!-- 主体信息 -->
          <view class="card-body">
            <!-- 第一行：标题 -->
            <view class="info-line title">
              {{ order.customer_name }} - {{ order.type }}
            </view>

            <!-- 第二行：联系方式 -->
            <view class="info-line row">
              <view class="left">电话：{{ order.phone }}</view>
              <!-- <view class="right">负责人：{{ order.member_name }}</view> -->
            </view>

            <!-- 第三行：日期信息 -->
            <view class="meta-line">
              <!-- 左侧日期信息 -->
              <view class="date-info">
                <view class="info-line">开始：{{ formatDate(order.start_date) }}</view>
                <view class="info-line">结束：{{ formatDate(order.end_date) }}</view>
              </view>

              <!-- 右侧档期信息 -->
              <view class="due-info">
                <view class="due-number">
                  <view class="number" v-if="getScheduleDays(order) > 0">
                    {{ getScheduleDays(order) }}
                  </view>
                  <view class="text" v-if="getScheduleDays(order) > 0">
                    天档期
                  </view>
                </view>
              </view>
            </view>

            <!-- 金额区块 -->
            <view class="amount-box">
              <view class="amount-item">
                <text class="amount-label">总金额</text>
                <text class="amount-value " style="color: var(--v-green);">{{ order.total_amount }}元</text>
              </view>
              <view class="amount-item">
                <text class="amount-label">已付金额</text>
                <text class="amount-value">{{ order.deposit }}元</text>
              </view>
              <view class="amount-item">
                <text class="amount-label">尾款</text>
                <text class="amount-value" style="color:var(--v-danger)">{{ order.final_payment }}元</text>
              </view>
            </view>
          </view>

          <!-- 底部操作 -->
          <view class="card-footer">
            <view class="action-buttons">
              <button class="edit-btn" @click="editOrder(order)">
                编辑订单
              </button>
              <button class="edit-btn" @click="handleMaterial(order)"
                :style="{ color: order.has_material > 0 ? '#69c33c' : 'var(--v-danger)', borderColor: order.has_material > 0 ? '#69c33c' : 'var(--v-danger)' }">
                {{ order.has_material > 0 ? "已上传" : "未上传" }}
              </button>
              <button class="complete-btn" @click="completeOrder(order)" v-if="order.status != '已完成'">
                项目完成
              </button>
              <button class="complete-btn disabled" v-else>已完成</button>
            </view>
          </view>
          <view class="finished" v-if="order.status == '已完成'">
            <view class="text">已完成</view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <s-empty v-if="orderList.length === 0 && !loading && !error"
        src="https://img01.yzcdn.cn/vant/empty-image-default.png" text="暂无订单数据"></s-empty>

      <!-- 加载错误提示 -->
      <view class="error-tips" v-if="error && !loading">
        <text>加载失败，请</text>
        <text class="retry" @click="retryLoad">点击重试</text>
      </view>

      <!-- 加载中提示 -->
      <view class="loading-more" v-if="loading">
        <s-icon name="loading" size="24" color="#999"></s-icon>
        <text>加载中...</text>
      </view>

      <!-- 没有更多提示 -->
      <view class="no-more" v-if="finished && orderList.length > 0">
        <text>没有更多了</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import sNavBar from '@/uni_modules/s-ui/components/s-nav-bar/s-nav-bar.vue'
import sIcon from '@/uni_modules/s-ui/components/s-icon/s-icon.vue'
import sEmpty from '@/uni_modules/s-ui/components/s-empty/s-empty.vue'

export default {
  components: {
    sNavBar,
    sIcon,
    sEmpty
  },
  data() {
    return {
      orderList: [], // 订单列表数据
      loading: false, // 加载状态
      finished: false, // 是否加载完成
      refreshing: false, // 是否正在刷新
      error: false, // 是否加载失败
      page: 1, // 当前页码
      pageSize: 10, // 每页数量
      filterDate: "", // 筛选日期
      filterType: "", // 筛选类型
      filterStatus: "", // 筛选状态
      typeOptions: [
        { text: "全部类型", value: "" },
        { text: "活动/商业", value: "活动/商业" },
        { text: "婚礼/策划", value: "婚礼/策划" },
        { text: "外景/约拍", value: "外景/约拍" },
      ],
      statusOptions: [
        { text: "全部状态", value: "" },
        { text: "待处理", value: "待处理" },
        { text: "已完成", value: "已完成" },
      ],
    };
  },
  computed: {
    // 预处理所有订单的渠道样式类，解决非H5平台不支持在:class中使用函数调用的问题
    processedOrderList() {
      return this.orderList.map(order => ({
        ...order,
        channelClass: this.getChannelClass(order.channel)
      }));
    }
  },
  onLoad() {
    this.loadOrders();
    this.getTypeList();
  },
  onShow() {
    this.loadOrders();
  },
  methods: {
    reachBottom() {
      this.loadOrders();
    },
    getTypeList() {
      this.sjuAjax.get("/category/list", {}, (res) => {
        if (res && res.code === 200) {
          let resArr = [
            {
              text: "全部类型",
              value: "",
            },
          ];
          if (res?.data?.list?.length > 0) {
            res.data.list.forEach((item, index) => {
              resArr.push({
                text: item.name,
                value: item.id,
              });
            });
          }
          this.typeOptions = resArr;
          console.log(this.typeOptions);
        }
      });
    },

    // 获取渠道样式类
    getChannelClass(channel) {
      if (!channel) return "";
      if (["线上", "线下", "门店"].includes(channel)) {
        return "channel-default";
      }
      return "channel-custom";
    },

    // 加载订单数据
    async loadOrders() {
      if (this.loading || this.finished) return;

      this.loading = true;
      this.error = false;

      try {
        const res = await this.sjuAjax.get("/order/list", {
          page: this.page,
          pageSize: this.pageSize,
          startDate: this.filterDate,
          type: this.filterType,
          status: this.filterStatus,
        });

        this.loading = false;
        this.refreshing = false;

        if (res.code === 200) {
          const data = res.data || {};
          const list = data.list || [];
          const pagination = data.pagination || {};

          if (this.page === 1) {
            this.orderList = list;
          } else {
            this.orderList = [...this.orderList, ...list];
          }
          if (
            list.length < this.pageSize ||
            this.page >= pagination.totalPages
          ) {
            this.finished = true;
          } else {
            this.page++;
          }
        } else {
          this.error = true;
          uni.showToast({
            title: res.msg || "加载失败",
            icon: "none",
          });
        }
      } catch (err) {
        this.loading = false;
        this.refreshing = false;
        this.error = true;
        uni.showToast({
          title: "网络错误，请重试",
          icon: "none",
        });
      }
    },

    // 重试加载
    retryLoad() {
      this.error = false;
      this.loadOrders();
    },

    // 处理下拉刷新
    handleRefresh() {
      this.refreshing = true;
      this.page = 1;
      this.finished = false;
      this.loadOrders();
    },

    // 刷新数据
    refreshOrders() {
      this.page = 1;
      this.finished = false;
      this.orderList = [];
      this.loadOrders();
    },

    // 日期变化
    changeDate(e) {
      this.filterDate = e.detail.value;
      this.refreshOrders();
    },

    // 类型变化
    changeType(e) {
      this.filterType = this.typeOptions[e.detail.value].value;
      this.refreshOrders();
    },

    // 状态变化
    changeStatus(e) {
      this.filterStatus = this.statusOptions[e.detail.value].value;
      this.refreshOrders();
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return "";
      return dateStr.split(" ")[0];
    },

    // 计算档期天数（结束日期-开始日期）
    getScheduleDays(order) {
      if (!order.start_date || !order.end_date) return 0;
      const startDate = new Date(order.start_date);
      const endDate = new Date(order.end_date);
      const diffTime = endDate - startDate;
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1; // +1 因为包括开始日期当天
      return diffDays;
    },

    // 获取状态颜色
    getDueColor(order) {
      if (!order.end_date) return "#4ECDC4";
      const endDate = new Date(order.end_date);
      const today = new Date();
      const diffTime = endDate - today;
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

      if (diffDays < 0) return "#FF6B6B";
      if (diffDays <= 3) return "#FFBE0B";
      return "#4ECDC4";
    },

    // 编辑订单
    editOrder(order) {
      uni.navigateTo({
        url: `/pages/order/edit?id=${order.id}`,
      });
    },
    handleMaterial(order) {
      console.log(order);
      uni.navigateTo({
        url: `/pages/material/upload?id=${order.id}`,
      });
    },
    // 标记订单完成
    completeOrder(order) {
      uni.showModal({
        title: "确认操作",
        content: `确定要将订单 ${order.order_number} 标记为已完成吗？`,
        success: (res) => {
          if (res.confirm) {
            this.sjuAjax.post("/order/complete", { id: order.id }, (res) => {
              if (res.code === 200) {
                uni.showToast({ title: "操作成功", icon: "success" });
                this.refreshOrders();
              } else {
                uni.showToast({ title: res.msg || "操作失败", icon: "none" });
              }
            });
          }
        },
      });
    },

    // 底部导航切换
    tabBarChange(url) {
      uni.switchTab({
        url: url,
      });
    },
  },
};
</script>
<style lang="less" scoped>
.indexPage {
  background-color: var(--v-bg);
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
}

.top-bg {
  width: 100%;
  height: 312rpx;
  border-radius: 0 0 24rpx 24rpx;
  // background: linear-gradient(red, blue);
  position: fixed;
  top: 0;
  left: 0;
  z-index: 0;
  overflow: hidden;
}

.fixed-filter {
  z-index: 10;
  padding: 0 30rpx;
}

.filter-bar {
  display: flex;
  padding: 20rpx 0;
  border-radius: 16rpx;

  .item {
    flex-grow: 1;
  }

  .filter-item {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    color: #333;
    background: rgba(255, 255, 255, 0.75);
    border-radius: 10rpx;
    margin: 0 10rpx;
    transition: all 0.2s;
    height: 66rpx;
    display: flex;
    align-items: center;

    >* {
      margin-right: 10rpx;

      /* Replaced gap: 10rpx */
      &:last-child {
        margin-right: 0;
        /* Remove margin from last child */
      }
    }

    &:active {
      background: #eee;
      transform: scale(0.98);
    }
  }
}

.main-scroll {
  flex-grow: 1;
  height: 0;
  box-sizing: border-box;
  padding-top: 20rpx;
}

.order-list {
  display: flex;
  flex-direction: column;
  padding: 0 30rpx 30rpx;

  .order-card {
    margin-bottom: 20rpx;

    /* Replaced gap: 20rpx */
    &:last-child {
      margin-bottom: 0;
      /* Remove margin from last child */
    }
  }
}

.order-card {
  background-color: var(--v-white);
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: var(--v-shadow);
  position: relative;

  &.disabled {

    background: #dddee8;

    .amount-item {
      background: #e8e9f4;
    }

    .edit-btn {
      opacity: .6;
    }

    .card-header,
    .card-footer {
      border-color: #c9c9c9;
    }
  }

  .finished {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    pointer-events: none;

    .text {
      font-size: 46rpx;
      color: rgba(0, 0, 0, .3);
      border-radius: 12rpx;
      border: rgba(0, 0, 0, .3) 6rpx solid;
      width: 180rpx;
      height: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translateX(-50%) translateY(-50%) rotate(25deg);
    }
  }
}

.card-header {
  padding: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid var(--v-bg);
  font-size: 26rpx;
  color: var(--v-gray);
}

.order-no {
  font-weight: bold;
}

.order-channel {
  color: var(--v-theme);

  /* 默认渠道样式 */
  &.channel-default {
    color: var(--v-theme);
    font-weight: bold;
  }

  /* 自定义渠道样式 */
  &.custom-channel {
    color: var(--v-orange);
    font-weight: bold;
    background-color: rgba(var(--v-orange-rgb), 0.1);
    padding: 4rpx 12rpx;
    border-radius: 20rpx;
    border: 1rpx solid var(--v-orange);
  }
}

.card-body {
  padding: 20rpx;
  padding-bottom: 0;
}

.info-line {
  font-size: 26rpx;
  color: var(--v-gray);
  margin-bottom: 16rpx;
  line-height: 1.5;

  &.row {
    display: flex;
    justify-content: space-between;
  }
}

.info-line.title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.meta-line {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  min-height: 80rpx;
}

.date-info {
  flex: 1;
}

.due-info {
  display: flex;
  align-items: baseline;
  margin-left: 20rpx;
}

.due-number {
  font-size: 28rpx;
  line-height: 1;
  color: var(--v-gray);
  display: flex;
  align-items: baseline;

  .number {
    margin-right: 10rpx;
    /* Replaced gap: 10rpx */
    font-size: 68rpx;
    color: var(--v-green);
  }
}

.amount-box {
  display: flex;
  justify-content: space-between;
  margin: 30rpx 0;
}

.amount-item {
  flex: 1;
  text-align: center;
  padding: 16rpx;
  background-color: var(--v-bg);
  border-radius: 8rpx;
  margin: 0 10rpx;

  &:first-child {
    margin-left: 0;
  }

  &:last-child {
    margin-right: 0;
  }
}

.amount-label {
  display: block;
  font-size: 26rpx;
  color: var(--v-gray);
  margin-bottom: 8rpx;
}

.amount-value {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: var(--v-theme);
}

.card-footer {
  padding: 20rpx;
  border-top: 1rpx solid var(--v-bg);
}

.action-buttons {
  display: flex;
  justify-content: space-between;
}

.edit-btn,
.complete-btn {
  height: 80rpx;
  line-height: 80rpx;
  font-size: 28rpx;
  border-radius: 8rpx;
  flex: 1;
  margin: 0 10rpx;
}

.edit-btn {
  background-color: var(--v-white);
  color: var(--v-theme);
  border: 1rpx solid var(--v-theme);
}

.complete-btn {
  background: var(--v-linear);
  color: var(--v-white);
  border: none;

  &.disabled {
    opacity: 0.6;
  }
}

.loading-more,
.no-more,
.error-tips {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx 0;
  font-size: 28rpx;
  color: #999;
}

.loading-more {
  s-icon {
    margin-right: 10rpx;
    animation: rotate 1s linear infinite;
  }
}

.error-tips {
  color: #ff6b6b;

  .retry {
    color: var(--v-theme);
    margin-left: 10rpx;
    text-decoration: underline;
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}
</style>